var DB_NAME =  "681a0817-5067-416f-9749-114beedebe52"; //"docmanagement";

var mongodb = require('mongodb');
var host = '10.4.4.130';  //'localhost';
var port = 25099; //27017;
var dbname = DB_NAME;
var connect = false;

var db;

exports.connect = function() {
	if (connect)
		return;
	var server = new mongodb.Server(host, port, {
		auto_reconnect : true
	});
	db = new mongodb.Db(dbname, server);
	db.open(function(err, db) {
		if (!err) {
			console.log("db open successfully!");
			connect = true;
		} else {
			console.log(err);
		}
	});
};

exports.find = function(tbname, handler) {
	if (connect) {
		db.collection(tbname, function(err, collection) {
			if (err) {
				handler(err, null);
			} else {
				collection.find().toArray(function(err, items) {
					handler(err, items);
				});
			}
		});
	}
};

exports.listQuery = function(tbname, key, handler) {
	if (connect) {
		db.collection(tbname, function(err, collection) {
			collection.find(key).toArray(function(err, items) {
				console.log('[dbMongo.listQuery], key is ' + key + ', result is ' + items);
				handler(null, items);
			});
		});
	} else {
		console.log('db not connected');
		handler('db not connected', null);
	}
};

// 查询全部，带条件.示例key:{age:20},sortKey:'name',
// sortOrder:-1(1升序-1降序),
// limitCount:5 查询个数
// limitFrom:10 跳过个数，从第多少个开始
exports.listQueryEx = function(tbname, key, sortKey, sortOrder, limitCount,
		limitFrom, handler) {
	if (connect) {
		var _sort = {
			sort : {
				sortKey : sortOrder
			}
		};
		var _limit = {
			limit : limitCount,
			skip : limitFrom
		};
		db.collection(tbname, function(err, collection) {
			collection.find(key, _sort, _limit).toArray(function(err, items) {
				handler(null, items);
			});
		});
	} else {
		console.log('db not connected');
		handler('db not connected', null);
	}
};

exports.add = function(tbname, item, handler) {
	if (connect) {
		db.collection(tbname, function(err, collection) {
			if (err) {
				handler(err, null);
			} else {
				collection.insert(item, function(err, item) {
					handler(err, item);
				});
			}
		});
	} else {
		console.log('db not connected');
		handler('db not connected', null);
	}
}
